package com.tsj.model.model.vo;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.*;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
/**
 * @author taoshujian
 * @version 1.0
 * @since 2025-10-24 00:09:46
 */
public class ExcelAttachmentExtractor {

    /**
     * 提取工作表中所有附件，并记录其关联的单元格
     */
    public static List<AttachmentInfo> extractAllAttachments(XSSFSheet sheet) throws IOException {
        List<AttachmentInfo> attachments = new ArrayList<>();

        // 获取工作表中的绘图容器（所有附件都在这里）
        XSSFDrawing drawing = sheet.getDrawingPatriarch();
        if (drawing == null) {
            return attachments; // 无附件
        }

        // 遍历所有形状（每个形状可能是图片或OLE附件）
        for (XSSFShape shape : drawing.getShapes()) {
            // 获取附件的坐标锚点（确定位置）
            XSSFAnchor anchor = shape.getAnchor();
            if (!(anchor instanceof XSSFClientAnchor)) {
                continue; // 跳过非单元格关联的附件
            }
            XSSFClientAnchor clientAnchor = (XSSFClientAnchor) anchor;

            // 根据锚点计算关联的单元格地址（如"A1"）
            String cellAddress = getCellAddressByAnchor(clientAnchor);

            // 提取附件信息（名称、类型、内容）
            if (shape instanceof XSSFPicture) {
                // 处理图片附件
                XSSFPicture picture = (XSSFPicture) shape;
                XSSFPictureData pictureData = picture.getPictureData();
                String ext = pictureData.suggestFileExtension();
                String fileName = "image_" + System.currentTimeMillis() + "." + (ext != null ? ext : "jpg");
                byte[] content = pictureData.getData();
                attachments.add(new AttachmentInfo(fileName, cellAddress, "图片", content));
            } else if (shape instanceof XSSFObjectData) {
                // 处理OLE附件（如PDF、Word等）
                XSSFObjectData objectData = (XSSFObjectData) shape;
                String fileName = objectData.getFileName();
                if (fileName == null || fileName.isEmpty()) {
                    fileName = "attachment_" + System.currentTimeMillis() + ".bin"; // 未知文件名
                }
                byte[] content = objectData.getObjectData();
                attachments.add(new AttachmentInfo(fileName, cellAddress, "OLE附件", content));
            }
        }

        return attachments;
    }

    /**
     * 根据附件的锚点坐标计算其主要关联的单元格地址（如"A1"）
     * 规则：取附件左上角所在的单元格
     */
    private static String getCellAddressByAnchor(XSSFClientAnchor anchor) {
        // 锚点的起始行和起始列（左上角位置）
        int rowIndex = anchor.getRow1();
        int colIndex = anchor.getCol1();

        // 转换列号为字母（如0→A，1→B...）
        String colLetter = getColumnLetter(colIndex);
        // 行号从1开始（Excel中行号从1起始）
        int rowNumber = rowIndex + 1;

        return colLetter + rowNumber;
    }

    /**
     * 将列索引（0-based）转换为Excel列字母（如0→A，25→Z，26→AA）
     */
    private static String getColumnLetter(int colIndex) {
        if (colIndex < 0) {
            return "";
        }
        StringBuilder sb = new StringBuilder();
        while (colIndex >= 0) {
            int remainder = colIndex % 26;
            sb.append((char) ('A' + remainder));
            colIndex = (colIndex / 26) - 1;
            if (colIndex < 0) {
                break;
            }
        }
        return sb.reverse().toString();
    }
}
